#include "client.h"
#include "ui_client.h"

Client::Client(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Client)
{
    ui->setupUi(this);

    this->setWindowTitle("客户端");

    this->clientSocket = new QTcpSocket(this);

    // 2. 点击链接服务器按钮时，建立与服务器的链接
    connect(ui->connBtn, &QPushButton::clicked, [this](){
        // 1) 获取ip地址和端口号
        QString ip = ui->ipLine->text();
        QString port = ui->portLine->text();

        // 2) 根据ip和端口号连接服务器
        this->clientSocket->connectToHost(ip, port.toUShort());
    });

    // 4. 客户端显示成功链接的信息
    // 当客户端与服务器成功链接时，会触发 QTcpSocket::connected 信号
    connect(this->clientSocket, &QTcpSocket::connected, [this](){
        ui->textEdit->setText("已成功与服务器链接");
    });

    // 5. 客户端发送数据给服务器端
    // 核心：发送数据就是将数据写入到 socket 中
    connect(ui->sendBtn, &QPushButton::clicked, [this](){
        // 1) 获取用户发送的信息
        QString msg = ui->msgLine->text();

        // 2) 将信息写入socket
        this->clientSocket->write(msg.toUtf8());
        ui->msgLine->clear();
    });

    // 当服务器发送数据过来时，会触发 QTcpSocket::readyRead 信号
    connect(this->clientSocket, &QTcpSocket::readyRead, [this](){
        QString msg = this->clientSocket->readAll();
        ui->textEdit->append(msg);
    });

    // 断开与服务器的链接
    connect(ui->disconnBtn, &QPushButton::clicked, [this](){
        this->clientSocket->disconnectFromHost();
    });

}

Client::~Client()
{
    delete ui;
}
